<template>
  <div>
    <div class="pageTitleWhole">
      <div style="color:#1890FF;float:left;margin-right:15px;cursor:pointer">
        <router-link :to="`/dataBI/operationReport?f=1`">
          <a-icon type="left" />返回
        </router-link>
      </div>
      <a-breadcrumb :routes="routes">
        <template slot="itemRender" slot-scope="{ route, routes, paths }">
          <span v-if="routes.indexOf(route) === routes.length - 1">{{ route.breadcrumbName }}</span>
          <router-link v-else :to="`${basePath}/${paths.join('/')}`">{{ route.breadcrumbName }}</router-link>
        </template>
      </a-breadcrumb>
    </div>
    <div id="takeoutMain">
      <a-form-model layout="inline" :model="form" style="margin-top:0px;">
        <a-form-model-item label="客户名称">
          <a-input v-model="form.custNameLike" />
        </a-form-model-item>
        <a-form-item label="所属部门">
          <a-tree-select
            class="selectInputWidth"
            v-model="form.deptId"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :load-data="onLoadData"
            :tree-data="deptTreeData"
            placeholder="请选择"
            @change="onChangeTree"
          ></a-tree-select>
        </a-form-item>
        <a-form-item label="所属销售">
          <a-select v-model="form.sellerId" class="selectInputWidth">
            <a-select-option value>全部</a-select-option>
            <a-select-option v-for="v in sellers" :key="v.uiId">{{v.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-model-item>
          <a-button type="primary" @click="check">查询</a-button>
        </a-form-model-item>
        <a-form-model-item>
          <a-button type="primary" @click="excelExport">导出Excel</a-button>
        </a-form-model-item>
      </a-form-model>
      <a-card style="text-align:center; margin-top:24px;">
        <a-row :gutter="[16]">
          <a-col :span="6" class="assent">
            <div class="assent_mes">总应收（元）</div>
            <div class="assent_shu">{{statistics.receivableAmount}}</div>
          </a-col>
          <a-col :span="6" class="assent">
            <div class="assent_mes">总应付（元）</div>
            <div class="assent_shu">{{statistics.payableAmount}}</div>
          </a-col>
          <a-col :span="6" class="assent">
            <div class="assent_mes">总毛利（元）</div>
            <div class="assent_shu">{{statistics.profit}}</div>
          </a-col>
          <a-col :span="6" class="assent">
            <div class="assent_mes">总箱量（个）</div>
            <div class="assent_shu">{{statistics.containerNum}}</div>
          </a-col>
          <!-- <a-col :span="4" class="assent">
            <div class="assent_mes">满载量（TEU）</div>
            <div class="assent_shu">{{statistics.loadingCapacity}}</div>
          </a-col>
          <a-col :span="4" class="assent">
            <div class="assent_mes">实装量（TEU）</div>
            <div class="assent_shu">{{statistics.actualLoadingCapacity}}</div>
          </a-col>
          <a-col :span="4">
            <div class="assent_mes">完成率</div>
            <div class="assent_shu">{{statistics.completeRateStr}}</div>
          </a-col>-->
        </a-row>
      </a-card>
      <a-table
        :columns="columns"
        :loading="loading"
        :data-source="data"
        style="margin-top:25px;"
        :scroll="{x:1800}"
        :pagination="pagination"
        :row-key="(record,index) => index"
      ></a-table>
    </div>
  </div>
</template>
<script>
import { querySellerDown, queryDeptDown } from '@/api'
import { commonExport } from '@/api/request'
import { queryOperatingReportDetailList, queryOperatingReportDetailListStatistics } from '@/api/dataBI'
const deptData = {
  type: 2, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL'
}
const sellerData = {
  type: 2, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL',
  status: 1
}
const columns = [
  {
    title: '序号',
    width: 80,
    customRender: (text, record, index) => {
      return index + 1
    }
  },
  {
    title: '起航日期',
    dataIndex: 'departureDate',
    customRender: (text, record, index) => {
      return record.departureDate || '--'
    },
    width: 180
  },
  {
    title: '船名航次',
    dataIndex: 'voyage',
    customRender: (text, record, index) => {
      return record.voyage || '--/--'
    },
    width: 200
  },
  {
    title: '客户名称',
    dataIndex: 'custName',
    width: 250
  },
  {
    title: '所属部门',
    dataIndex: 'department',
    width: 280
  },
  {
    title: '所属销售',
    dataIndex: 'seller'
  },
  {
    title: '应收金额（元）',
    dataIndex: 'receivableAmount',
    customRender: (text, record, index) => {
      return record.receivableAmount.toFixed(2)
    }
  },
  {
    title: '应付金额（元）',
    dataIndex: 'payableAmount',
    customRender: (text, record, index) => {
      return record.payableAmount.toFixed(2)
    }
  },
  {
    title: '毛利（元）',
    dataIndex: 'profit',
    customRender: (text, record, index) => {
      return record.profit.toFixed(2)
    }
  },
  // {
  //   title: '毛利率',
  //   dataIndex: 'profitRateStr'
  // },
  {
    title: '箱量（个）',
    dataIndex: 'containerNum'
  }
  // {
  //   title: '装载量（TEU）',
  //   dataIndex: 'actualLoadingCapacity'
  // }
]
export default {
  props: ['id'],
  data () {
    return {
      deptTreeData: [],
      sellers: [],
      basePath: '/dataBI',
      routes: [
        {
          path: '/operationReport',
          breadcrumbName: '运营报表'
        },
        {
          path: '',
          breadcrumbName: '详情'
        }
      ],
      shipNameList: [],
      form: {
        voyageId: '',
        custNameLike: '',
        deptId: '',
        sellerId: ''
      },
      pageNum: 1,
      pageSize: 10,
      loading: true,
      data: [],
      columns,
      pagination: {},
      statistics: {}
    }
  },
  methods: {
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDeptDown({ parentId: treeNode.dataRef.key, ...deptData }).then(
          rsp => {
            let childrenData = []
            rsp.data.forEach(value => {
              childrenData.push({
                title: value.name,
                key: value.deptId,
                value: value.deptId
              })
            })
            treeNode.dataRef.children = childrenData
            this.deptTreeData = [...this.deptTreeData]
            resolve()
          }
        )
      })
    },
    initDept (e) {
      queryDeptDown(e).then(rsp => {
        let initData = []
        rsp.data.forEach((value, index) => {
          initData.push({
            title: value.name,
            key: value.deptId,
            value: value.deptId
          })
        })
        this.deptTreeData = initData
      })
    },
    onChangeTree (value) {
      this.initSellerDown(value)
    },
    initSellerDown (deptId) {
      querySellerDown({ ...sellerData, deptId }).then(rsp => {
        this.sellers = rsp.data.map((v, i) => {
          if (!v.uiId) {
            v.name = '请选择'
            v.uiId = ''
          }
          return v
        })
      })
    },
    shipReportListRequest (e) {
      this.loading = true
      queryOperatingReportDetailList(e)
        .then(res => {
          this.data = res.data.list
          let currentPage = this.pageNum
          this.pagination = {
            current: currentPage,
            pageSize: res.data.pageSize,
            total: res.data.total,
            showQuickJumper: false,
            showSizeChanger: true,
            pageSizeOptions: ['10', '30', '50', '100', '500'],
            showTotal: total =>
              `共${total}条记录 第${currentPage}/${res.data.pages}页`,
            onChange: pageNum => {
              this.pageNum = pageNum
              let paramData = {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                ...this.form
              }
              this.shipReportListRequest(paramData)
            },
            onShowSizeChange: (current, size) => {
              this.pageNum = current
              this.pageSize = size
              let paramData = {
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                ...this.form
              }
              this.shipReportListRequest(paramData)
            }
          }
          this.loading = false
        })
        .catch(rs => { })
    },
    shipStatisticsRequest (e) {
      queryOperatingReportDetailListStatistics(e)
        .then(res => {
          // // console.log(res.data)
          res.data.receivableAmount = res.data.receivableAmount.toFixed(2)
          res.data.payableAmount = res.data.payableAmount.toFixed(2)
          res.data.profit = res.data.profit.toFixed(2)
          this.statistics = res.data
        })
        .catch(rs => { })
    },
    onChange (date, dateString) {
      this.form.startDate = dateString[0]
      this.form.endDate = dateString[1]
    },
    check () {
      this.pageNum = 1
      this.shipStatisticsRequest({
        ...this.form
      })
      this.shipReportListRequest({
        ...this.form,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    },
    excelExport () {
      commonExport('/containerReport/exportOperatingReportDetailList', {
        ...this.form,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: this.columns
      })
    }
  },
  mounted () {
    this.form.voyageId = this.id
    this.initDept(deptData) // 所属部门
    this.initSellerDown() // 所属销售
    this.shipStatisticsRequest({
      ...this.form
    })
    this.shipReportListRequest({
      ...this.form,
      pageNum: this.pageNum,
      pageSize: this.pageSize
    })
  }
}
</script>

<style lang="less" scoped>
#takeoutMain {
  padding: 24px;
  margin: 24px;
  background: #fff;
  min-height: 700px;
}
</style>
